﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Expression.Encoder.Live;
using Microsoft.Expression.Encoder;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.IO;
using System.Threading;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        LiveJob jobL;
        public string job;
        public string output;
        public string server="localhost\\SQLEXPRESS";
        public string user="sa";
        public string password="KU2013";
        public string database="KU";
        public string source = "1";
        DataBase dbc = null;
        //DataBase dbc = new DataBase(@"localhost\SQLEXPRESS", "sa", "KU2013", "KU");

        private const int WM_COPYDATA = 0x4A;
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        public static string StartPath
        {
            get
            {
                return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
            }
        }

        public Form1()
        {
            InitializeComponent();
            Hide();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dbc=new DataBase(server, user, password, database);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Opacity = 0;
            this.Visible = false;
            this.ShowInTaskbar = false;
            string pref="";
            if (job.Contains("1")) {pref="1";}
            else if (job.Contains("2")) {pref="2";}
            else if (job.Contains("3")) {pref="3";}
            else if (job.Contains("4")) { pref = "4"; }
            this.Text="ExpressionRecorder"+pref;
            //while (readLock()) { }
            //if (writeLock() == false) { Form1_Load(sender, e); }
            System.IO.StreamWriter file = new System.IO.StreamWriter(StartPath + "/log" + pref + ".txt", false);
            file.WriteLine("new live job");
            jobL = new LiveJob();
            file.WriteLine("before load "+job);
            jobL.Load(StartPath + "/"+job);
            Thread.Sleep(3000);
            file.WriteLine("after load");
            jobL.PublishFormats.Clear();
            string outfile = output.Replace(".wmv", "_" + DateTime.Now.ToShortDateString().Replace(".", "") + "_" + DateTime.Now.ToShortTimeString().Replace(":", "") + ".wmv");
            FileArchivePublishFormat archive = new FileArchivePublishFormat() { OutputFileName = outfile };
            string identifier = this.Handle.ToString();
            dbc.sqlExecute("insert into Records(RecordFile,StartDate,StartTime,Source,Identifier,FileName) values ('" + outfile + "','" + DateTime.Now.ToShortDateString() + "','" + DateTime.Now.ToLongTimeString() + "','" + source + "','" + identifier + "','" + Path.GetFileName(outfile) + "')");
            jobL.PublishFormats.Add(archive);
            file.WriteLine("before start " + outfile);
            jobL.StartEncoding();
           // Thread.Sleep(5000);
            file.WriteLine("after start");
            file.Flush();
            file.Close();
            //writeUnLock();
        }

        private bool readLock()
        {
            try
            {
                System.IO.StreamReader file = new System.IO.StreamReader(StartPath + "/lock.lck");
                string lc = file.ReadLine();
                file.Close();
                if (lc.Equals("0")) { return false; }
                else { return true; }
            }
            catch (Exception ex) { return false; }
        }

        private bool writeLock()
        {
            bool done = false;
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(StartPath + "/lock.lck", false);
                file.WriteLine("1");
                file.Flush();
                file.Close();
                done = true;
            }
            catch (Exception ex) { }
            return done;
        }

        private void writeUnLock()
        {
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(StartPath + "/lock.lck", false);
                file.WriteLine("0");
                file.Flush();
                file.Close();
            }
            catch (Exception ex) { writeUnLock(); }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //jobL.StopEncoding();
        }

        public void stop(){
          jobL.StopEncoding();
          string identifier = this.Handle.ToString();
          string sql = "update Records set StopDate='" + DateTime.Now.ToShortDateString() + "', StopTime='" + DateTime.Now.ToLongTimeString() + "' where identifier='" + identifier + "' and StopDate is Null and StopTime is Null";   
          dbc.sqlExecute(sql);
          Close();
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_COPYDATA:
                    COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                    Type mytype = mystr.GetType();
                    mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                    if (mystr.lpData.Equals("stop")){stop();};
                    break;
            }
            base.WndProc(ref m);
        }
    }
}
